    //
    //  HouseRentingListViewController.m
    //  smart_village
    //
    //  Created by shaorui on 15/1/30.
    //  Copyright (c) 2015年 osoons. All rights reserved.
    //

#import "CommentViewController.h"
#import "LocationAndObserver.h"
#import "DemoTableHeaderView.h"
#import "DemoTableFooterView.h"

#import "UITopBanner.h"

#import "commentsCell.h"

#import "AFNetworking.h"
#import "LoadingView.h"
#import "BaseUrlConfig.h"
#import "NetWarningView.h"
//







@interface CommentViewController ()
{
    CGFloat heightCell_;
    BOOL    isFirstShow_;
    NSInteger currentPage_;
}
    // Private helper methods
- (void) addItemsOnTop;
- (void) addItemsOnBottom;
//- (NSString *) createRandomValue;
@end

@implementation CommentViewController
#pragma mark - life cycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
            // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
        // Do any additional setup after loading the view from its nib.
    heightCell_ = 0;
    _needUpdate = NO;
    isFirstShow_ = YES;
    
    [self InitTableView];//初始化tableview
    self.canLoadMore = YES; //标识可以读更多
    self.pullToRefreshEnabled = YES;//可以刷新
    
    _vTopBanner.parentController = self.navigationController;
    [_vTopBanner.lalTitel setText:@"评价"];
    [_vTopBanner.btnGoback setHidden:NO];
    [_vTopBanner.btnGoback addTarget:self action:@selector(backTo:) forControlEvents:UIControlEventTouchUpInside];
    
}
-(void)backTo:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
-(void)viewDidAppear:(BOOL)animated
{
    if (isFirstShow_)
        {
        isFirstShow_ = NO;
            //
        [self.tableView removeFromSuperview];
        
        CGRect frame = _vTableBg.frame;
        frame.origin = CGPointZero;
        [self.tableView setFrame:frame];
        [self.vTableBg addSubview:self.tableView];
        
        heightCell_ = frame.size.width * 103/400;
        [self RequestWith:1];
        
        }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
}

-(void)InitTableView
{
    
        // set the custom view for "pull to refresh". See DemoTableHeaderView.xib.
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DemoTableHeaderView" owner:self options:nil];
    DemoTableHeaderView *headerView = (DemoTableHeaderView *)[nib objectAtIndex:0];
    self.headerView = headerView;
    
        // set the custom view for "load more". See DemoTableFooterView.xib.
    nib = [[NSBundle mainBundle] loadNibNamed:@"DemoTableFooterView" owner:self options:nil];
    DemoTableFooterView *footerView = (DemoTableFooterView *)[nib objectAtIndex:0];
    self.footerView = footerView;
    
    
        //user nib
    UINib *nibCell = [UINib nibWithNibName:NSStringFromClass([commentsCell class]) bundle:nil];
    [self.tableView registerNib:nibCell forCellReuseIdentifier:[NSString stringWithFormat:@"%@", [commentsCell class]]];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _arrData = [[NSMutableArray alloc] init];
}

#pragma mark - standard tableview datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
        // Return the number of sections.
    return 1;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdent = @"commentsCell";
        //    //uinib method
    commentsCell *cell = (commentsCell *)[tableView dequeueReusableCellWithIdentifier:cellIdent];
//            [cell cellWithData:[_arrData  objectAtIndex:indexPath.row]];
        //
    [cell layoutIfNeeded];
    [cell updateConstraintsIfNeeded];
    CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    
    NSLog(@"高度 %f", height);
    
        //    return height;
    return 129;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

            if([_arrData count])
                {
                return [_arrData count];
                }
            else
                {
                return 10;
                }

    
}


#pragma mark - Standard TableView delegates
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
        static NSString *cellIdent = @"commentsCell";        //uinib method
    commentsCell * Cell = (commentsCell *)[tableView dequeueReusableCellWithIdentifier:cellIdent];
    Cell.selectionStyle = UITableViewCellSelectionStyleNone;

    
    
    
    return Cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    
}

#pragma mark - 刷新与加载事件
    //刷新完成示例
- (void) addItemsOnTop
{
    
    [_arrData removeAllObjects];
    [self RequestWith:1];
}

    //加载更多完成示例
- (void) addItemsOnBottom
{
    [self RequestWith:(currentPage_ + 1)];
}


#pragma mark - View actions
-(void)UpdateViewContents
{
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (_needUpdate) {
        _needUpdate = NO;
        [self UpdateViewContents];
    }
}

#pragma mark -
#pragma mark - 以下方法基本固定可以不改
#pragma mark - Pull to Refresh
- (void) pinHeaderView
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    [super pinHeaderView];
    
        // do custom handling for the header view
    DemoTableHeaderView *hv = (DemoTableHeaderView *)self.headerView;
    [hv.activityIndicator startAnimating];
    hv.title.text = Loading;
}

- (void) unpinHeaderView
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    [super unpinHeaderView];
    
        // do custom handling for the header view
    [[(DemoTableHeaderView *)self.headerView activityIndicator] stopAnimating];
}

    // Update the header text while the user is dragging
- (void) headerViewDidScroll:(BOOL)willRefreshOnRelease scrollView:(UIScrollView *)scrollView
{
    DemoTableHeaderView *hv = (DemoTableHeaderView *)self.headerView;
    if (willRefreshOnRelease)
        hv.title.text = ReleaseRefresh;
    else
        hv.title.text = PullDownoRefresh;
}


    // refresh the list. Do your async calls here.
- (BOOL) refresh
{
    
    if (![super refresh])
        return NO;
    
        // Do your async call here
        // This is just a dummy data loader:
    [self performSelector:@selector(addItemsOnTop) withObject:nil afterDelay:2.0];
    
    
    return YES;
}

#pragma mark - Load More
- (void) willBeginLoadingMore
{
    NSLog(@"will begin loading ");
    DemoTableFooterView *fv = (DemoTableFooterView *)self.footerView;
    [fv.activityIndicator startAnimating];
}

    // Do UI handling after the "load more" process was completed. In this example, -footerView will
    // show a "No more items to load" text.
- (void) loadMoreCompleted
{
    [super loadMoreCompleted];
    
    DemoTableFooterView *fv = (DemoTableFooterView *)self.footerView;
    [fv.activityIndicator stopAnimating];
    
    if (!self.canLoadMore)
        {
            // Do something if there are no more items to load
            // We can hide the footerView by: [self setFooterViewVisibility:NO];
            // Just show a textual info that there are no more items to load
        fv.infoLabel.hidden = NO;
        fv.infoLabel.text  = TemporarilyNoData;
        
        }
}

- (BOOL) loadMore
{
    if (![super loadMore])
        return NO;
    
        // Do your async loading here
    [self performSelector:@selector(addItemsOnBottom) withObject:nil afterDelay:2.0];
        // See -addItemsOnBottom for more info on what to do after loading more items
    
    return YES;
}

-(void)setCellData:(NSArray *)arrData
{
    _arrData = [[NSMutableArray alloc] initWithArray:arrData];
}


#pragma mark - controller events
-(void)tapCallNumber:(UIButton *)button
{
        //    BusinessModel *modelTmp = [_arrData objectAtIndex:button.tag];
        //
        //
        //    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"是否拨打"
        //                                                       delegate:self
        //                                              cancelButtonTitle:@"取消"
        //                                         destructiveButtonTitle:nil
        //                                              otherButtonTitles:modelTmp.telephone, nil];
        //    [sheet dismissWithClickedButtonIndex:1 animated:YES];
        //    [sheet setTag:0];
        //    [sheet showInView:self.view];
    
}


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (actionSheet.tag) {
        case 0:
        {
            if (buttonIndex == 0)
                {
                NSURL *phoneNumberURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@", [actionSheet buttonTitleAtIndex:0]]];
                [[UIApplication sharedApplication] openURL:phoneNumberURL];
                }
        }
            break;
        default:
            break;
    }
}

#pragma mark - network req

-(void)RequestWith:(NSInteger)page
{
    [[LoadingView shareLoadingView] show];
    
    
        
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    

    
    NSString * strUrl = [NSString stringWithFormat:@"%@%@", HostServer, nil];
    
    NSDictionary *params = @{
                             
                             @"repair.id":[NSNumber numberWithInteger:self.strRepaiIid.integerValue],
                             @"page":[NSNumber numberWithInteger:page]
                             };
    
    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
     NSDictionary *dicRespon = responseObject;
     [self RequestSuccessWith:dicRespon];
     
     [[LoadingView shareLoadingView] dismissAnimated:YES];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
     [[LoadingView shareLoadingView] dismissAnimated:YES];
     [[NetWarningView sharedNetWarningView] show];  //警告网络异常
     NSLog(@"Error: %@", error);
     }];
}

-(void)RequestSuccessWith:(NSDictionary *)dicRespon
{
    NSInteger code = [[dicRespon objectForKey:@"return"] integerValue];
    if (code == 1)
        {
            //        currentPage_
        
        
        NSArray *arrBussi = [dicRespon objectForKey:@"data"];
        if (arrBussi && [arrBussi isKindOfClass:[arrBussi class]])
            {
            [_arrData removeAllObjects];
            for (NSDictionary *dicTmp in arrBussi)
                {
                NSError *error = nil;
//                hs_repair_order_replyModel *modelTmp =
//                [MTLJSONAdapter modelOfClass:[hs_repair_order_replyModel class] fromJSONDictionary:dicTmp error:&error];
//                if(error == nil)
//                    {
//                    [_arrData addObject:modelTmp];
//                    }
                }
            
            [self.tableView reloadData];
            }
        }
    else if (code == 3)
        {
        self.canLoadMore = NO;
        }
    else
        {
        NSString *str = [dicRespon objectForKey:@"info"];
        UIAlertView *alertView =
        [[UIAlertView alloc] initWithTitle:@"提示"  message:str delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
        }
    
    [self refreshCompleted];
    [self loadMoreCompleted];

}


-(void)ratingChanged:(float)newRating {
//    ratingLabel.text = [NSString stringWithFormat:@"Rating is: %1.1f", newRating];
}


@end
